//
//  DLKeyChainManager.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/12/6.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLKeyChainManager.h"
#import "DLKeyChain.h"


static NSString * const KEY_IN_KEYCHAIN_UUID = @"TheOnlyIdentification_KEY_UUID";
static NSString * const KEY_UUID = @"TheOnlyIdentification_key_uuid";


@implementation DLKeyChainManager


+ (NSString *)createUUID {
    NSString *timestampString = [NSString stringWithFormat:@"%.lf", [[NSDate date] timeIntervalSince1970]];
    NSString *headerString = [DLKeyChainManager randomStringWithlength:5];
    NSString *tailString = [DLKeyChainManager randomStringWithlength:8];
    return [NSString stringWithFormat:@"%@%@%@", headerString, timestampString, tailString];
}

+ (NSString *)randomStringWithlength:(int)length {
    srand((unsigned)time(NULL));
    int randNumber;
    char randString[length];
    for (int i = 0; i < length; ++i) {
        switch (arc4random()%3) {
            case 2:// 小写字母
                randNumber = 97;
                randNumber += rand()%26;
                break;
                
            default:// 数字
                randNumber = 48;
                randNumber += arc4random()%10;
                break;
        }
        randString[i] = randNumber;
    }
    randString[length]='\0';
    
    return [NSString stringWithFormat:@"%s", randString];
}

+ (void)saveUUID:(NSString *)UUID {
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:UUID forKey:KEY_UUID];
    [DLKeyChain save:KEY_IN_KEYCHAIN_UUID data:usernamepasswordKVPairs];
}

+ (NSString *)readUUID {
    NSMutableDictionary *usernamepasswordKVPair = (NSMutableDictionary *)[DLKeyChain load:KEY_IN_KEYCHAIN_UUID];
    return [usernamepasswordKVPair objectForKey:KEY_UUID];
}

+ (void)deleteUUID {
    [DLKeyChain delete:KEY_IN_KEYCHAIN_UUID];
}


@end
